import SvgIcon from '@c/SvgIcon';
import gsap from 'gsap';
import React, { useEffect, useRef } from 'react';

export default function Index({ onChecked }) {
  const ref = useRef();
  const wrapper = useRef();
  const [checked, setChecked] = React.useState(false);

  useEffect(() => {
    const them = localStorage.getItem('them') || 'light';
    if (them === 'dark') {
      handleChecked();
    }
  }, []);

  const handleChecked = () => {
    const animation = {
      duration: 0.5,
      left: 0,
      translateX: 0,
      ease: 'power2.inOut',
    };
    const wrapperAnimation = {
      duration: 0.5,
      ease: 'power2.inOut',
    };

    const sunAnimation = {
      duration: 0.5,
      top: 0,
      ease: 'power2.inOut',
    };

    const moonAnimation = {
      duration: 0.5,
      top: 36,
      ease: 'power2.inOut',
    };

    if (!checked) {
      animation.left = '100%';
      animation.translateX = '-100%';

      moonAnimation.top = 0;

      sunAnimation.top = 36;
    }
    gsap.to(ref.current, animation);
    gsap.to(wrapper.current, wrapperAnimation);
    gsap.to('.moon', moonAnimation);
    gsap.to('.sun', sunAnimation);
    setChecked(!checked);
    onChecked && onChecked(!checked);
  };

  return (
    <div
      className="bg-transparent border border-gray-500 rounded-[15px] h-6 relative py-[2px] px-1 box-border w-12 cursor-pointer"
      onClick={handleChecked}
      ref={wrapper}
    >
      <div
        ref={ref}
        className="backdrop-blur-lg rounded-full w-6 h-6 absolute left-[0] -top-[1px] -translate-x-[0] cursor-pointer scale-90 switch-btn flex justify-center items-center overflow-hidden"
      >
        <div className="rounded-full w-6 h-6 top-0 bottom-0 left-0 right-0 bg-base-200 absolute opacity-40"></div>
        <SvgIcon name={'moon'} className="w-4 h-4 relative top-9 moon left-2"></SvgIcon>
        <SvgIcon name={'sun'} className="w-4 h-4 relative sun -left-2"></SvgIcon>
      </div>
    </div>
  );
}
